//
//  AppDelegate.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/26.
//

import UIKit
import Alamofire
import IQKeyboardManager

@available(iOS 10.0, *)
@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var netWorkType: Int? = 0
    var timer: Timer?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        IQKeyboardManager.shared().isEnabled = true
        IQKeyboardManager.shared().isEnableAutoToolbar = true
        IQKeyboardManager.shared().shouldShowToolbarPlaceholder = false
                
        // check network
        currentNetReachability()
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(checkNetwork), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)
        return true
    }

    // MARK: UISceneSession Lifecycle
    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    
    @objc func checkNetwork() {
        if netWorkType == 0 {
            showAlert()
            currentNetReachability()
        }
    }
    
    func showAlert() {
        let alertController = UIAlertController(title: "", message: "`海铁货运`当前无法连接到网络，请检查APP是否打开网络连接设置", preferredStyle: .alert)
        let settingAction = UIAlertAction(title: "设置", style: .destructive, handler: {(action) in
            self.timer?.invalidate()
            self.timer = nil
            let url = URL(string: UIApplication.openSettingsURLString)
            if UIApplication.shared.canOpenURL(url!) {
                UIApplication.shared.open(url!, options: [:], completionHandler: nil)
            }
        })
        alertController.addAction(settingAction)
        UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
    }
    
    func currentNetReachability() {
        let manager = NetworkReachabilityManager()
        manager?.listener = { status in
            switch status {
            case .unknown:
                self.netWorkType = 0
                break
            case .notReachable:
                self.netWorkType = 0
                break
            case .reachable:
                self.netWorkType = 1
                NotificationCenter.default.post(name: NSNotification.Name("refresh"), object: self, userInfo: nil)
                self.timer?.invalidate()
                self.timer = nil
                break
            }
        }
        manager?.startListening()
    }
    
}
